const crypto = require("crypto");
const MongoDao = require("../service/dao/MongoDao");
const _ = require("underscore");

class UserService {
	/**
	 * 验证用户
	 * @param user
	 * @param isHashed password是否已经经过哈希加密(如果是从cookie当中获得,就是加密过的)
	 * @param successCb 验证通过的回调函数
	 * @param failedCb 验证不通过的回调函数
	 * @returns {boolean}
	 */
	checkUser (user, isHashed, successCb, failedCb) {
		if(!isHashed) {
			//md5加密
			const hashPwd = crypto.createHash("md5");
			hashPwd.update(user.password);
			user.password = hashPwd.digest("hex");
		}

		MongoDao.User.find({username:user.username,password:user.password},function(err,users){
			if(err) return console.error(err);
			if(users.length != 0) {
				if(_.isFunction(successCb)) {
					successCb.call(this, users[0]);
				}
			} else {
				if(_.isFunction(failedCb)) {
					failedCb.call();
				}
			}
		});
	}

}

module.exports = new UserService();